package com.xinchao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xinchao.core.constant.BusinessConstant;
import com.xinchao.core.constant.CmccApiConstant;
import com.xinchao.core.constant.ModuleConstant;
import com.xinchao.core.exception.ServiceException;
import com.xinchao.core.util.CmccApiUtils;
import com.xinchao.core.util.DateUtils;
import com.xinchao.core.util.NumberUtils;
import com.xinchao.dao.DeviceMapper;
import com.xinchao.dao.DeviceSimInfoMapper;
import com.xinchao.model.DeviceSimInfo;
import com.xinchao.model.OperationLog;
import com.xinchao.model.User;
import com.xinchao.model.dto.CityCmccInfoDTO;
import com.xinchao.model.dto.DeviceSimInfoActivationTimeDTO;
import com.xinchao.model.dto.DeviceSimInfoTrafficDTO;
import com.xinchao.model.vo.DeviceDetailVO;
import com.xinchao.model.vo.DeviceSimInfoVO;
import com.xinchao.service.CityCmccInfoService;
import com.xinchao.service.DeviceSimInfoService;
import com.xinchao.service.OperationLogService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 终端sim卡信息Service实现类
 * @author dxy
 * @date 2018/8/15 10:40
 */
@Service(value = "deviceSimInfoService")
public class DeviceSimInfoServiceImpl implements DeviceSimInfoService {
	private static Logger logger = LoggerFactory.getLogger(DeviceSimInfoServiceImpl.class);
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private DeviceSimInfoMapper deviceSimInfoMapper;
	@Autowired
	private OperationLogService operationLogService;
	@Autowired
	private CityCmccInfoService cityCmccInfoService;
	@Autowired
	DeviceMapper deviceMapper;
	/**
	 * 保存终端sim卡信息
	 * @param deviceSimInfo DeviceSimInfo
	 */
	@Override
	public void saveDeviceSimInfo(DeviceSimInfo deviceSimInfo) {
		if (deviceSimInfo != null) {
			deviceSimInfoMapper.insertDeviceSimInfo(deviceSimInfo);
		}
	}

	/**
	 * 修改终端sim卡信息
	 * @param deviceSimInfo DeviceSimInfo
	 */
	@Override
	public void updateDeviceSimInfo(DeviceSimInfo deviceSimInfo) {
		if (deviceSimInfo != null) {
			deviceSimInfoMapper.updateDeviceSimInfo(deviceSimInfo);
		}
	}

	@Override
	public DeviceSimInfoVO selectByDeviceCode(String deviceCode) {
		DeviceSimInfoVO deviceSimInfoVO = deviceSimInfoMapper.selectByDeviceCode(deviceCode);
		if(null != deviceSimInfoVO){
			//当月流量预警,保留两位有效小数，第三位小数大于0时第二位小数+1
			String currentMonthTraffic = deviceSimInfoVO.getCurrentMonthTraffic();
			if(StringUtils.isNotBlank(currentMonthTraffic)){
				if (currentMonthTraffic.endsWith(BusinessConstant.DATA_UNIT_M)) {
					currentMonthTraffic = currentMonthTraffic.substring(0, (currentMonthTraffic.length() - 1));
				}
				currentMonthTraffic = NumberUtils.parseDouble(currentMonthTraffic);
				deviceSimInfoVO.setCurrentMonthTraffic(currentMonthTraffic);
			}

			//历史总流量,保留两位有效小数，第三位小数大于0时第二位小数+1
			String historicalTotalTraffic = deviceSimInfoVO.getHistoricalTotalTraffic();
			if(StringUtils.isNotBlank(historicalTotalTraffic)){
				if (historicalTotalTraffic.endsWith(BusinessConstant.DATA_UNIT_M)) {
					historicalTotalTraffic = historicalTotalTraffic.substring(0, (historicalTotalTraffic.length() - 1));
				}
				historicalTotalTraffic = NumberUtils.parseDouble(historicalTotalTraffic);
				deviceSimInfoVO.setHistoricalTotalTraffic(historicalTotalTraffic);
			}

			//上行速率转成Mbps ,保留两位小数
			String upStreamSpeed = deviceSimInfoVO.getUpStreamSpeed();
			if(StringUtils.isNotBlank(upStreamSpeed)){
				double upStreamSpeedDouble = Double.parseDouble(upStreamSpeed) / 1024;
				deviceSimInfoVO.setUpStreamSpeed(NumberUtils.parseDouble(upStreamSpeedDouble));
			}

			//下行速率转成Mbps ,保留两位小数
			String downStreamSpeed = deviceSimInfoVO.getDownStreamSpeed();
			if(StringUtils.isNotBlank(downStreamSpeed)){
				double downStreamSpeedDouble = Double.parseDouble(downStreamSpeed) / 1024;
				deviceSimInfoVO.setDownStreamSpeed(NumberUtils.parseDouble(downStreamSpeedDouble));
			}
			
			// str_to_date
			String activationTime = deviceSimInfoVO.getActivationTime();
			if(StringUtils.isNotBlank(activationTime)){
				deviceSimInfoVO.setActivationTime(DateUtils.StringDateFormat(activationTime, DateUtils.PATTEN_YMDHMS, DateUtils.PATTEN_YMD_HMS));
			}
		}
		return deviceSimInfoVO;
	}

	/**
	 * 获取终端sim卡信息总数
	 * @param city 城市
	 * @return Long
	 * @throws ServiceException
	 */
	@Override
	public Long countDeviceSimInfo(String city) throws ServiceException {
		if (StringUtils.isBlank(city)) {
			throw new ServiceException("输入参数不能为空");
		}
		return deviceSimInfoMapper.countDeviceSimInfo(city);
	}

	/**
	 * 获取第一个终端sim卡信息流量（升序排列）
	 * @param city 城市
	 * @return DeviceSimInfoTrafficDTO
	 * @throws ServiceException
	 */
	@Override
	public DeviceSimInfoTrafficDTO selectFirstDeviceSimInfoTraffic(String city) throws ServiceException {
		if (StringUtils.isBlank(city)) {
			throw new ServiceException("输入参数不能为空");
		}
		return deviceSimInfoMapper.selectFirstDeviceSimInfoTraffic(city);
	}

	/**
	 * 获取终端流量信息列表
	 * @param city 城市
	 * @param startId 起始ID
	 * @param endId 结束ID
	 * @param rows 条数
	 * @return List<DeviceSimInfoTrafficDTO>
	 * @throws ServiceException
	 */
	@Override
	public List<DeviceSimInfoTrafficDTO> listDeviceSimInfoTraffic(String city, Long startId, Long endId, Long rows) throws ServiceException {
		if (StringUtils.isBlank(city) || startId == null || endId == null || rows == null) {
			throw new ServiceException("输入参数不能为空");
		}
		return deviceSimInfoMapper.listDeviceSimInfoTraffic(city, startId, endId, rows);
	}

	/**
	 * 更新终端sim卡信息当月流量
	 * @throws ServiceException
	 */
	@Override
	public void updateDeviceSimInfoMonthTraffic(DeviceSimInfoTrafficDTO dto) throws ServiceException {
		if (dto == null) {
			throw new ServiceException("输入参数不能为空");
		}
		deviceSimInfoMapper.updateDeviceSimInfoMonthTraffic(dto);
	}

	/**
	 * 获取没有激活时间的终端sim卡信息总数
	 * @param city 城市
	 * @return Long
	 */
	@Override
	public Long countDeviceSimInfoNoActivationTime(String city) {
		if (StringUtils.isNotBlank(city)) {
			return deviceSimInfoMapper.countDeviceSimInfoNoActivationTime(city);
		}
		return 0L;
	}

	/**
	 * 获取第一个终端sim卡信息激活时间（升序排列）
	 * @return DeviceSimInfoTrafficDTO
	 * @throws ServiceException
	 */
	@Override
	public DeviceSimInfoActivationTimeDTO selectFirstDeviceSimInfoActivationTime(String city) throws ServiceException {
		if (StringUtils.isBlank(city)) {
			throw new ServiceException("输入参数不能为空");
		}
		return deviceSimInfoMapper.selectFirstDeviceSimInfoActivationTime(city);
	}

	/**
	 * 获取终端信息激活时间列表
	 * @param city 城市
	 * @param startRow 开始行
	 * @param endRow 结束行
	 * @return List<DeviceSimInfoTrafficDTO>
	 * @throws ServiceException
	 */
	@Override
	public List<DeviceSimInfoActivationTimeDTO> listDeviceSimInfoActivationTime(String city, Long startRow, Long endRow) throws ServiceException {
		if (startRow == null || endRow == null || city == null) {
			throw new ServiceException("输入参数不能为空");
		}
		return deviceSimInfoMapper.listDeviceSimInfoActivationTime(city, startRow, endRow);
	}

	/**
	 * 更新终端sim卡信息激活时间
	 * @throws ServiceException
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateDeviceSimInfoActivationTime(DeviceSimInfoActivationTimeDTO dto) throws ServiceException {
		if (dto == null) {
			throw new ServiceException("输入参数不能为空");
		}
		deviceSimInfoMapper.updateDeviceSimInfoActivationTime(dto);
	}

	/**
	 * 设置SIM卡状态(0:启用 1:关停)
	 * hanqr 2018-08-16
	 *
	 * @param deviceCodes 终端唯一编码
	 * @param simStatus   SIM卡状态(0:启用 1:关停)
	 * @param loginUser   当前登录用户
	 * @param ip          操作ip
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void setSimStatus(String deviceCodes, Integer simStatus, User loginUser, String ip) throws ServiceException {
		// 操作内容
		StringBuilder deviceMsg = new StringBuilder("");
		//城市对应的集团编码，应用键对应值，密钥的MAP
		Map<String, CityCmccInfoDTO> cityCmccInfoMap = cityCmccInfoService.getCityCmccInfoMap();
		String[] deviceCodeArray = deviceCodes.split(",");
		// 循环操作每一个终端
		for (String deviceCode : deviceCodeArray) {
			// 根据deviceCode查询终端信息
			DeviceDetailVO deviceDetailVO = deviceMapper.getDeviceDetailByDeviceCode(deviceCode);
			if (deviceDetailVO != null) {
				deviceMsg.append(",");
				deviceMsg.append(deviceDetailVO.getMachineNumber());
			}
			// 根据deviceCode查询终端SIM卡信息
			DeviceSimInfoVO deviceSimInfoVo = deviceSimInfoMapper.selectByDeviceCode(deviceCode);
			if(deviceSimInfoVo != null) {
				// msisdn
				String msisdn = deviceSimInfoVo.getMsisdn();
				// 操作类型（1：停；2：开）
				Integer optTpye = simStatus == 0 ? CmccApiConstant.SIM_OPTTPYE_ENABLE : CmccApiConstant.SIM_OPTTYPE_DISABLE;
				// 是否多个终端
				// 方法名
				// 当前终端sim卡所在城市
				String simCity = deviceSimInfoVo.getSimCity();
				// 当前终端sim卡的appKeyValue、secret、groupCode
				String appKeyValue = null;
				String secret = null;
				String groupCode = null;
				if (cityCmccInfoMap != null && cityCmccInfoMap.size() > 0) {
					CityCmccInfoDTO cityCmccInfoDTO = cityCmccInfoMap.get(simCity);
					if(cityCmccInfoDTO != null) {
						appKeyValue = cityCmccInfoDTO.getAppKey();
						secret = cityCmccInfoDTO.getSecrect();
						groupCode = cityCmccInfoDTO.getGroupCode();
					}
				}
				// 调用移动接口设置SIM卡状态
				String result = CmccApiUtils.switchSim(CmccApiConstant.TRIOPI_BUSINESS_GPRS_SWITCH, msisdn, false, optTpye,appKeyValue, secret, groupCode);
				// 处理返回结果
				JSONObject  resultObject = JSONObject.parseObject(result);
				if(resultObject != null) {
					int code = resultObject.getIntValue(CmccApiConstant.CMCC_RESPONSE_CODE);
					if(code != 0) {
						// 办理失败
						String error = CmccApiConstant.ERROR_CODE_MAP.get(code);
						throw new ServiceException(error);
					}
				}
				// 设置dmp_device_sim_info表
				deviceSimInfoMapper.setSimStatus(deviceCode, simStatus);
			}
		}

		// 保存操作日志
		OperationLog operationLog = new OperationLog();
		StringBuilder statusMsg = new StringBuilder("");
		if (BusinessConstant.STATUS_ENABLE == simStatus) {
			statusMsg.append("启用");
		} else if (BusinessConstant.STATUS_DISABLE == simStatus) {
			statusMsg.append("关停");
		}
		String operationMsg = String.format("操作行为：%s. 操作对象：[终端:%s]", statusMsg + "SIM卡", deviceMsg.substring(1));
		operationLog.setOperationContent(operationMsg);
		operationLog.setOperationModule(ModuleConstant.MODULE_DEVICE_MNG);
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setOperationIp(ip);
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 *
	 * @param dto
	 * @throws ServiceException
	 */
	@Override
	public void updateDeviceSimInfoHistoryTraffic(DeviceSimInfoTrafficDTO dto) throws ServiceException {
		if (dto == null) {
			throw new ServiceException("输入参数不能为空");
		}
		deviceSimInfoMapper.updateDeviceSimInfoHistoryTraffic(dto);
	}

}
